#include "imInput.h"

using namespace imInput;

InputLib::InputLib(void) {
	hInst = NULL;
	hDLL = NULL;
	InputDev[0] = NULL;
	InputDev[1] = NULL;
	InputDev[2] = NULL;

	_CreateInputDevice = 0;
}
InputLib::InputLib(HINSTANCE hInstance) {
	hInst = hInstance;
	hDLL = NULL;
	InputDev[0] = NULL;
	InputDev[1] = NULL;
	InputDev[2] = NULL;

	_CreateInputDevice = 0;
}

InputLib::~InputLib(void) {
	Release();
}

HRESULT InputLib::MountLib(char *chAPI) {
	char buffer[300];

	HRESULT hr = S_OK;

	hDLL = LoadLibrary(chAPI);

	if(!hDLL) {
		_snprintf_s(buffer, 300, "Unable to load input library '%s'", chAPI);
		MessageBox(NULL, buffer, "Imagine - Error", MB_OK | MB_ICONERROR);
		return E_FAIL;
	}

	// Pointer to DLL function 'CreateRenderDevice'
	_CreateInputDevice = (CREATEINPUTDEVICE) GetProcAddress(hDLL, "CreateInputDevice");

	if( !_CreateInputDevice ) {
		MessageBox(NULL,
			"Unable to find CreateInputDevice function.",
			"Imagine - Error", MB_OK | MB_ICONERROR);
		return E_FAIL;
	}

	// Call DLL function to create the device
	hr = _CreateInputDevice(hDLL, &InputDev[0], IN_KEYBOARD);
	hr = _CreateInputDevice(hDLL, &InputDev[1], IN_MOUSE);

	InputDev[0]->Init(hInst, NULL);
	InputDev[1]->Init(hInst, NULL);

	return hr;
}

void InputLib::Release(void) {
	RELEASEINPUTDEVICE _ReleaseInputDevice = 0;
		
	if(hDLL) {
		_ReleaseInputDevice = (RELEASEINPUTDEVICE) GetProcAddress(hDLL, "ReleaseInputDevice");
	};
} // Release

iInputDevice* InputLib::GetDevice(InputDevType Type) {
	if(InputDev[Type] == NULL) {
		_CreateInputDevice(hDLL, &InputDev[Type], Type);
		InputDev[Type]->Init(hInst, NULL);
	};
	return InputDev[Type];
}